class Clock:
    """
    定义可以用来控制32x16的点阵屏类
    """
    def __init__(self):
#         self.dp()
        self.se = 0
        self.rtc = RTC()
        self.ntp()  # 调用这个方法来联网设置时间
        self.second_light = False

    def ntp(self):
#         self.connect_wifi()
        time.sleep(2)
        ntptime.host="ntp1.aliyun.com"
        ntptime.NTP_DELTA = 3155644800  # 东八区 UTC+8偏移时间（秒）
        try:
            ntptime.settime()
            print("联网成功...")
        except Exception as e:
            pass

    def show_time(self):
        # 获取真正的时间
        date = self.rtc.datetime()
        hour = date[4]
        minute = date[5]
        print("minute:",minute)
        if hour == 22 and minute >= 02:
            for i in range (100):
                led.value(1)
                time.sleep(0.5)
                led.value(0)
                time.sleep(0.5)
            
def door():
    p2.duty_u16(8000)
    time.sleep(0.5)
    p2.duty_u16(1700)
    time.sleep(3)
    p2.duty_u16(8000)
    time.sleep(0.5)

def do_connect():
      # 停
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('303', '303303303')
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
    return wlan.ifconfig()[0]

def handle_request(client_socket):
    """
    处理浏览器发送过来的数据
    然后回送相对应的数据（html、css、js、img。。。）
    :return:
    """     
    # 1. 接收
    recv_content = client_socket.recv(1024).decode("utf-8")
    lines = recv_content.splitlines()  # 将接收到的http的request请求数据按照行进行切割到一个列表中
    # 2. 处理请求
    # 提取出浏览器发送过来的request中的路径
    # GET / HTTP/1.1
    # GET /index.html HTTP/1.1
    # .......
    # lines[0]

    # 提取出/index.html 或者 /
    request_file_path = re.match(r"[^/]+(/[^ ]*)", lines[0]).group(1)

    print("----提出来的请求路径是：----")
    print(request_file_path)
    
    print("test---1---")

    # 完善对方访问主页的情况，如果只有/那么就认为浏览器要访问的是主页
    if request_file_path == "/" or "/opendoor":
        request_file_path = "/home.html"
        door()
 
    try:
        # 取出对应的文件的数据内容
        with open(request_file_path, "rb") as f:
            content = f.read()
    except Exception as ret:
        # 如果要是有异常，那么就认为：找不到那个对应的文件，此时就应该对浏览器404
        print(ret)
        door()
        response_headers = "HTTP/1.1 404 Not Found\r\n"
        response_headers += "Connection: close\r\n"
        response_headers += "Content-Type:text/html;charset=utf-8\r\n"
        response_headers += "\r\n"
        response_boy = "----推门就完事-------"
        response = response_headers + response_boy
        # 3.2 给浏览器回送对应的数据
        client_socket.send(response.encode("utf-8"))
        print("test---5---")
    else:
        # 如果要是没有异常，那么就认为：找到了指定的文件，将其数据回送给浏览器即可
        response_headers = "HTTP/1.1 200 OK\r\n"
        response_headers += "Connection: close\r\n"
        response_headers += "Content-Type:text/html;charset=utf-8\r\n"
        response_headers += "\r\n"
        response_boy = content
        response = response_headers.encode("utf-8") + response_boy
        # 3.2 给浏览器回送对应的数据
        client_socket.send(response)
        print("test---6---")

    # 4. 关闭套接字
    client_socket.close()
    print("test---7---")


def tcp_server_control_led():
    print("---1---")
    # 1. 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 为了保证在tcp先断开的情况下，下一次依然能够使用指定的端口，需要设置
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print("---2---")
    # 2. 绑定本地信息
    tcp_server_socket.bind(("", 80))
    print("---3---")
    # 3. 变成监听套接字
    tcp_server_socket.listen(128)

    print("---4---")
    while True:
        # 4. 等待客户端的链接
        client_socket, client_info = tcp_server_socket.accept()
        print("---5---")
        print(client_info)  # 打印 当前是哪个客户端进行了请求
        print("---6---")        
        # 5. 为客户端服务
        try:
            handle_request(client_socket)
        except Exception as ret:
            door()
            print("error:", ret)            
    print("---7---")
    # 6. 关闭套接字    
    tcp_server_socket.close()
